package com.sec.etech.form.cust.controller;

import com.alibaba.fastjson.JSONObject;
import com.sec.etech.file.service.EtechWebUploaderService;
import com.sec.etech.form.cust.util.FormDefDataUtil;
import io.swagger.annotations.ApiOperation;
import org.openbpm.base.api.aop.annotion.CatchErr;
import org.openbpm.base.api.constant.IStatusCode;
import org.openbpm.base.api.exception.BusinessException;
import org.openbpm.base.api.response.impl.ResultMsg;
import org.openbpm.base.core.util.StringUtil;
import org.openbpm.base.rest.util.RequestUtil;
import org.openbpm.bus.api.constant.BusinessPermissionObjType;
import org.openbpm.bus.api.model.IBusinessData;
import org.openbpm.bus.api.model.IBusinessObject;
import org.openbpm.bus.api.model.IBusinessPermission;
import org.openbpm.bus.api.service.IBusinessDataService;
import org.openbpm.bus.api.service.IBusinessObjectService;
import org.openbpm.bus.api.service.IBusinessPermissionService;
import org.openbpm.form.api.constant.FormStatusCode;
import org.openbpm.form.manager.FormDefManager;
import org.openbpm.form.model.FormDef;
import org.openbpm.form.rest.controller.FormDefDataController;
import org.openbpm.form.service.FormDefDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping({"/etech/formDefData/"})
public class EtechFormDefDataController extends FormDefDataController {

    @Autowired
    protected FormDefManager formDefManager;
    @Autowired
    protected IBusinessDataService businessDataService;
    @Autowired
    protected IBusinessObjectService businessObjectService;
    @Autowired
    protected IBusinessPermissionService businessPermissionService;

    @Autowired
    FormDefDataService formDefDataService;
    @Resource
    EtechWebUploaderService etechWebUploaderService;

    @Override
    @RequestMapping({"saveData"})
    @CatchErr(
            write2response = true,
            value = "保存formDef中的data数据异常"
    )
    public ResultMsg<JSONObject> saveData(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject data) throws Exception {
        String formKey = RequestUtil.getString(request, "key");
        boolean isSql = RequestUtil.getBoolean(request, "sql", false);
        JSONObject fileData = new JSONObject();
        if (data != null) {
            if (data.getJSONArray("add_file_list") != null) {
                fileData.put("add_file_list", data.getJSONArray("add_file_list"));
                data.remove("add_file_list");
            }
            if (data.getJSONArray("del_file_list") != null) {
                fileData.put("del_file_list", data.getJSONArray("del_file_list"));
                data.remove("del_file_list");
            }
            // 检查公用更新字段
            for (String key1 : data.keySet()) {
                JSONObject itemJson = data.getJSONObject(key1);
                FormDefDataUtil.checkCommonUpdateDate(itemJson);
                data.put(key1, itemJson);
            }
        }
        FormDef formDef = this.formDefManager.getByKey(formKey);
        String boKey = formDef.getBoKey();
        // 增加表单修改日志记录
        String logType = RequestUtil.getString(request, "log_type");
        JSONObject result = this.formDefDataService.saveFormDefData(data, formKey, isSql);
        // 保存表单后操作文件
        etechWebUploaderService.handlerFileAfterSaveForm(fileData);
        return this.getSuccessResult(result, "保存数据成功");
    }

    @ApiOperation("删除formDef中的data数据(delField=active/delValue=0表示逻辑删除的字段和值)")
    @RequestMapping({"removeData2/{formKey}/{id}"})
    @CatchErr(write2response = true, value = "删除formDef中的data数据异常")
    public ResultMsg removeData2(@PathVariable(value = "formKey", required = false) String formKey,
                                 @PathVariable(value = "id", required = false) String id
    ) throws Exception {
        if (StringUtil.isEmpty(formKey)) {
            throw new BusinessException("formKey 不能为空", (IStatusCode) FormStatusCode.PARAM_ILLEGAL);
        }
        if (StringUtil.isEmpty(id)) {
            throw new BusinessException("ID 不能为空", (IStatusCode) FormStatusCode.PARAM_ILLEGAL);
        }
        FormDef formDef = this.formDefManager.getByKey(formKey);
        String boKey = formDef.getBoKey();

        IBusinessPermission permission = this.businessPermissionService.getByObjTypeAndObjVal(BusinessPermissionObjType.FORM.getKey(), formKey, formDef.getBoKey(), true);
        IBusinessObject businessObject = this.businessObjectService.getFilledByKey(boKey);
        businessObject.setPermission(permission.getBusObj(boKey));

        Boolean logicDel = true;
        String delField = "active";
        String delValue = "0";

        String[] ids = id.split(",");
        if (ids.length > 1){
            for (String iii : ids){
                // 逻辑删除(临时方案，需要优化）
                if (!StringUtils.isEmpty(delField)) {
                    if (StringUtils.isEmpty(delValue)) {
                        delValue = "1";
                    }
                    IBusinessData bd = this.businessDataService.loadData(businessObject, iii);
                    bd.put(delField, delValue);
                    this.businessDataService.saveData(bd);
                } else {
                    this.businessDataService.removeData(businessObject, iii);
                }
            }
        }else{
            // 逻辑删除(临时方案，需要优化）
            if (!StringUtils.isEmpty(delField)) {
                if (StringUtils.isEmpty(delValue)) {
                    delValue = "1";
                }
                IBusinessData bd = this.businessDataService.loadData(businessObject, id);
                bd.put(delField, delValue);
                this.businessDataService.saveData(bd);
            } else {
                this.businessDataService.removeData(businessObject, id);
            }
        }



        return getSuccessResult("删除成功！");
    }

    // TODO will support 业务数据导入导出
    //importBoExcel
    //exportBoExcel
}
